import csv,sys

class AutoVivification(dict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value

def readMatrix(input_file,mat):
    matreader = csv.reader(open(input_file, 'r'), delimiter='\t')

    colheaders = matreader.next()[1:]

    for line in matreader:

        rowheader = line[0]
        data = line[1:]
        paired_data = zip(colheaders,data)
        for pair in paired_data:
            mat[rowheader][pair[0]] = pair[1]

def writeMatrix(mat,output_file):

    allcolheaders = set()

    for rowheader in mat.keys():
        allcolheaders = allcolheaders | set(mat[rowheader].keys())

    fset = frozenset(allcolheaders)

    matrixwriter = csv.writer(open(output_file,'w'),delimiter='\t')

    colheaders = [x for x in fset]
    colheaders.insert(0,'')

    matrixwriter.writerow(colheaders)

    for rowheader in mat.keys():
        rowlist = [mat[rowheader].get(x,'NA') for x in fset]
        rowlist.insert(0,rowheader)
        matrixwriter.writerow(rowlist)
            




assert sys.argv[1] != sys.argv[2] != sys.argv[3]

mat = AutoVivification()

readMatrix(sys.argv[1],mat)
readMatrix(sys.argv[2],mat)
writeMatrix(mat,sys.argv[3])

    
